import Vue from 'vue'
import router from './router'
import store from './store'
import { getQueryParameters } from '@/utils/util';

// progress bar
import NProgress from 'nprogress'
// progress bar custom style
import '@/components/NProgress/nprogress.less'
import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN } from '@/store/mutation-types'

import queryString from 'query-string'

// NProgress Configuration
NProgress.configure({ showSpinner: false })

// no redirect whitelist
const whiteList = ['login', 'sso', '404']
const defaultRoutePath = '/dashboard'
router.beforeEach((to, from, next) => {
  // start progress bar
  NProgress.start()
  to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${domTitle}`)
  const token = Vue.ls.get(ACCESS_TOKEN)
  const redirect = decodeURIComponent(from.query.redirect || to.path)
  if (token) {
    /* has token */
    if (to.path === '/login') {
      const options = getQueryParameters();
      store.dispatch('GetInfo').then(res => {
        if (options.redirect) {
          // 如果是从其他项目跳转过来的
          window.location.href = `${options.redirect}?token=${token}`;
        } else {
          next({ path: from.path })
        }
      }).catch(() => {
        store.dispatch('Logout').then(() => {
          next({ query: { redirect: options.redirect } })
        })
      })
    } else if (to.path === '/404') {
      next()
    } else if (to.path === '/') {
      next({ path: defaultRoutePath })
    } else {
      new Promise(res => {
        if (store.getters.userInfo.id) {
          res(store.getters.userInfo)
        } else {
          res(store.dispatch('GetInfo'))
        }
      })
        .then(res => {
          if (store.getters.addRouters.length === 0) {
            store
              .dispatch('GetAuth', {
                userId: res.id,
                role: res.role,
                appId: 0,
                useType: 'Web',
                status: 1
              })
              .then(() => {
                router.addRoutes(store.getters.addRouters)
                if (to.path === redirect) {
                  // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                  next({
                    ...to,
                    replace: true
                  })
                } else {
                  // 跳转到目的路由
                  next({
                    path: redirect
                  })
                }
              })
              .catch(() => {
                if (to.path !== '/dashboard') {
                  next({ path: defaultRoutePath })
                } else {
                  next()
                }
              })
          } else if (to.matched.length === 0) {
            let fromPath = from.path === '/login' ? defaultRoutePath : from.path === '/' ? defaultRoutePath : from.path
            next({ path: '/404', query: { 'redirect': fromPath } })//404页面内容可以自定义
          } else {
            if (to.path === redirect) {
              next()
            } else {
              // 跳转到目的路由
              next({
                path: redirect
              })
            }
          }
        })
        .catch(() => {
          next({ path: '/login' })
        })
    }
  } else {
    // 是否是扫码回调地址
    const callbackToken = to.query.token || queryString.parse(location.search).token
    if (callbackToken) {
      Vue.ls.set(ACCESS_TOKEN, callbackToken, 7 * 24 * 60 * 60 * 1000)
      next({ path: defaultRoutePath, replace: true })
      return
    }
    if (whiteList.includes(to.name)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next({ path: '/login' })
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
